package com.llyb.tingshu.common.login;

import com.llyb.tingshu.common.constant.RedisConstant;
import com.llyb.tingshu.common.execption.GuiguException;
import com.llyb.tingshu.common.result.ResultCodeEnum;
import com.llyb.tingshu.common.util.AuthContextHolder;
import com.llyb.tingshu.model.user.UserInfo;
import io.netty.util.internal.StringUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
@Aspect
@Slf4j
public class TsLoginAspect {


    @Autowired
    private RedisTemplate redisTemplate;

    @Around("@annotation(tsLogin)")
    public Object doTsLogin(ProceedingJoinPoint joinPoint,TsLogin tsLogin) throws Throwable {
        Object result;

        try {
            // 获取当前线程上请求头上是否携带token
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
            HttpServletRequest request = servletRequestAttributes.getRequest();
            String token = request.getHeader("token");
            if (tsLogin.required()){
                if (token == null) {
                    log.info("token is null");
                    throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
                }
                String userLoginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;

                UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(userLoginKey);
                if (null == userInfo) {
                    log.info("userInfo is null");
                    throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
                }
            }

            // 保存用户信息到map并返回
            if (StringUtils.hasText(token)) {
                String userLoginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
                UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(userLoginKey);
                if (null != userInfo) {
                    AuthContextHolder.setUserId(userInfo.getId());
                }
            }

            result = joinPoint.proceed();
        } finally {
            AuthContextHolder.removeUserId();
        }

        return result;
    }
}
